package com.younion.util;

import java.io.IOException;
import java.io.InputStream;

import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.HttpStatus;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.params.HttpClientParams;
import org.apache.http.conn.scheme.PlainSocketFactory;
import org.apache.http.conn.scheme.Scheme;
import org.apache.http.conn.scheme.SchemeRegistry;
import org.apache.http.conn.ssl.SSLSocketFactory;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.impl.conn.tsccm.ThreadSafeClientConnManager;
import org.apache.http.params.BasicHttpParams;
import org.apache.http.params.HttpConnectionParams;
import org.apache.http.params.HttpParams;
import org.apache.http.params.HttpProtocolParams;
import org.apache.http.util.EntityUtils;
/**
 * @author Devin.Hu
 * @date 2011-6-24
 * @version V1.0
 * @description HttpClientUtils工具类，用于与服务端建立连接，传送或读取数据
 */
public class HttpClientUtils {

	private String charset = "UTF-8";

	private static ThreadSafeClientConnManager cm = null;

	static {
		SchemeRegistry schemeRegistry = new SchemeRegistry();
		schemeRegistry.register(new Scheme("http", 80, PlainSocketFactory.getSocketFactory()));
		schemeRegistry.register(new Scheme("https", 443, SSLSocketFactory.getSocketFactory()));
		cm = new ThreadSafeClientConnManager(schemeRegistry);
		// Increase max total connection to 200
		cm.setMaxTotal(600);
		// Increase default max connection per route to 20
		cm.setDefaultMaxPerRoute(300);
		// Increase max connections for localhost:80 to 50
		// HttpHost localhost = new HttpHost("locahost", 80);
		// cm.setMaxForRoute(new HttpRoute(localhost), 50);

	}

	/**
	 * 得到HttpClient方法
	 * 
	 * @return
	 */

	public static HttpClient getHttpClient(int timeOut) {
		HttpParams httpParams = new BasicHttpParams();

		// 判断手机客户端连接的cmwap网络，设置代理
		// if(isWap()){
		// // MyLog.error(HttpClientUtils.class,
		// "***************************cmwap***********************");
		// HttpHost proxy = new HttpHost("10.0.0.172", 80,"http");
		// //10.0.0.200
		// httpParams.setParameter(ConnRouteParams.DEFAULT_PROXY, proxy);
		// }

		// 连接建立时的毫秒级超时时间
		HttpConnectionParams.setConnectionTimeout(httpParams, timeOut * 1000);
		// 套接字的毫秒级超时时间
		HttpConnectionParams.setSoTimeout(httpParams, timeOut * 1000);
		HttpConnectionParams.setSocketBufferSize(httpParams, 8192);

		HttpClientParams.setRedirecting(httpParams, true);

		String userAgent = "Mozilla/5.0 (Windows; U; Windows NT 5.1; zh-CN; rv:1.9.2) Gecko/20100115 Firefox/3.6";
		HttpProtocolParams.setUserAgent(httpParams, userAgent);

		// return new DefaultHttpClient(httpParams);
		// 通过连接池返回
		return new DefaultHttpClient(cm, httpParams);

	}

	/**
	 * 执行doGet方法
	 * 
	 * @param url
	 * @return
	 * @throws Exception
	 */
	public String doGet(String url) {
		// 使用工具默认编码
		return doGet(url, charset);
	}

	public String doGet(String url, String charset) {
		/* 建立HTTPGet对象 */
		String strResult = "";
		HttpEntity entity = null;
		HttpResponse httpResponse = null;
		HttpClient httpClient = null;
		HttpGet httpRequest = null;
		/* 发送请求并等待响应 */
		try {
			httpClient = getHttpClient(30);
			httpRequest = new HttpGet(url);
			httpResponse = httpClient.execute(httpRequest);
			entity = httpResponse.getEntity();
			strResult = EntityUtils.toString(entity, charset);
			strResult = filterHtml(strResult);
		} catch (Exception e) {
			try {
				if (entity != null) {
					EntityUtils.consume(entity);
				}
			} catch (IOException e1) {
			}
			httpRequest.abort();
			e.printStackTrace();
		} finally {
			// 通过连接池管理则不需要关闭
			// httpClient.getConnectionManager().shutdown();
		}
		return strResult;
	}

	/**
	 * 执行doGet方法，失败返回null
	 * 
	 * @param url
	 * @return InputStream
	 */
	public InputStream doGet4stream(String url) throws ClientProtocolException, IOException {
		HttpGet httpRequest = new HttpGet(url);
		HttpResponse httpResponse = getHttpClient(60).execute(httpRequest);

		if (httpResponse.getStatusLine().getStatusCode() == HttpStatus.SC_OK) {
			return httpResponse.getEntity().getContent();
		}
		return null;
	}

	/**
	 * 过滤特殊字符
	 * 
	 * @param result
	 * @return
	 */
	private String filterHtml(String result) {
		if (null != result) {
			result = result.replace("&#039;", "'");
			result = result.replace("&amp;", "&");
			result = result.replace("&nbsp;", " ");
		}
		return result;
	}

	// // 判断网络类型
	// public static boolean isWap() {
	// String proxyHost = android.net.Proxy.getDefaultHost();
	// if (proxyHost != null) {
	// return true;
	// } else {
	// return false;
	// }
	// }

}
